
<template>
  <a-card :bordered="false" :bodyStyle="{ padding: '24px 16px', height: '100%' }">
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="48">
          <a-col :md="8" :sm="24">
            <a-form-item label="搜索学员：">
              <a-input
                v-model="keywords"
                placeholder="请搜索学员"
                style="width:80%;"
                @pressEnter="$refs.table.refresh(true)"
              >
                <a-tooltip slot="suffix" title="请搜索学员">
                  <a-icon
                    type="search"
                    style="color: rgba(0,0,0,.45)"
                    @click="$refs.table.refresh()"
                  />
                </a-tooltip>
              </a-input>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <a-form-item label="报读课程">
              <a-select
                v-model="queryParam.course_id"
                placeholder="请选择报读课程"
                allowClear
                style="width:80%;"
              >
                <a-select-option
                  v-for="(item,index) in courseList"
                  :key="index"
                  :value="item.id"
                >{{item.name}}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <a-form-item label="所在班级">
              <a-select
                v-model="queryParam.class_id"
                placeholder="请选择班级"
                allowClear
                style="width:80%;"
              >
                <a-select-option
                  v-for="(item,index) in classList"
                  :key="index"
                  :value="item.id"
                >{{item.name}}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <template v-if="advanced">
            <a-col :md="8" :sm="24">
              <a-form-item label="跟进人:">
                <a-select
                  v-model="queryParam.user_id"
                  placeholder="请选择跟进人"
                  allowClear
                  style="width:80%;"
                >
                  <a-select-option
                    v-for="(item,index) in userList"
                    :key="index"
                    :value="item.id"
                  >{{item.name}}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="学管师:">
                <a-select
                  v-model="queryParam.academic_supervisor"
                  placeholder="请选择学管师"
                  allowClear
                  style="width:80%;"
                >
                  <a-select-option
                    v-for="(item,index) in userList"
                    :key="index"
                    :value="item.id"
                  >{{item.name}}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="是否超上">
                <a-checkbox @change="handleChange2">有超上</a-checkbox>
              </a-form-item>
            </a-col>
          </template>
        </a-row>
      </a-form>
    </div>
    <a style="cursor:pointer" v-if="advanced" @click="more" id="moreButton">
      收起
      <a-icon type="up"></a-icon>
    </a>
    <a style="cursor:pointer" v-if="!advanced" @click="more" id="moreButton">
      展开
      <a-icon type="down"></a-icon>
    </a>
    <div class="table-operator">
      <a-button
        style="margin-right:10px;"
        type="primary"
        :disabled="!hasSelected"
        @click="batchRemind"
      >批量提醒</a-button>
      <a-button @click="visible=true">预警设置</a-button>
    </div>
    <a-alert
      type="warning"
      :message="'预警值： 剩余课时  ≤  '+settingObjCopy.class_hour+'  课时 或 剩余天数  ≤  '+settingObjCopy.class_time+'  天'"
      banner
      class="expand_warning"
    />
    <s-table
      ref="table"
      :columns="columns"
      :data="loadData"
      class="user_management_table"
      :row-selection="{ selectedRowKeys: selectRows, onChange: onSelectChange }"
      style="margin-top:20px;"
      :pagination="pagination"
      :scroll="{x:1500}"
    >
      <a slot="no" slot-scope="text,record">
        <router-link
          :to="{name:'student_Info',query:{id:record.student_id}}"
          key="/educationalCenter/studentExpand/studentInfo"
        >
          <a :title="record.student_name">{{record.student_name}}</a>
        </router-link>
      </a>
      <div slot="number" slot-scope="text, record">
        <div v-if="record.price_type==1">
          {{record.ksnum}}课时
          <div v-if="record.go_beyond">
            （超上
            <span style="color:red;">{{record.go_beyond}}课时）</span>
          </div>
        </div>
        <div v-else>
          {{record.daynum}}天
          <div v-if="record.go_beyond">
            （超上
            <span style="color:red;">{{record.go_beyond}}天）</span>
          </div>
        </div>
      </div>
      <span slot="action" slot-scope="text, record">
        <a
          @click="signUp(record.student_id,record.structures_id,record.project_id||null)"
        >续费</a>
        <a-divider type="vertical" />
        <a @click="remind(record)">续费提醒</a>
      </span>
      <span slot="last_remind_time" slot-scope="text,record">
        <span v-if="record.last_remind_time">{{record.last_remind_time|formatDate}}</span>
        <span v-else>-</span>
      </span>
    </s-table>
    <a-modal
      title="预警设置"
      :visible="visible"
      @ok="settingTime"
      :confirmLoading="confirmLoading"
      @cancel="handleCancel"
    >
      满足以下条件的学员将进入续费预警列表：
      <br />
      <br />
      <span style="color:#666">
        剩余课时&nbsp;≤&nbsp;
        <a-input-number :min="0" :max="9999999999999999999" v-model="settingObj.class_hour" />&nbsp;或&nbsp;剩余天数&nbsp;≤&nbsp;
        <a-input-number :min="0" :max="9999999999999999999" v-model="settingObj.class_time" />
      </span>
    </a-modal>
    <create-form ref="createModal" @ok="handleOk" />
  </a-card>
</template>

<script>
import moment from 'moment'
import { STable, Ellipsis } from '@/components'
import CreateForm from '@/views/list/modules/CreateForm'
import { contractList, getContractSetting, contractSetting, contractRemind } from '@/api/contract'
import { coursesList } from '@/api/courseCharge'
import { classList } from '@/api/class'
import { accountList } from '@/api/account'
export default {
  name: 'TableList',
  components: {
    STable,
    Ellipsis,
    CreateForm,
  },
  data() {
    return {
      pagination:{
        showTotal:total=>`共${total}条数据`,
      },
      mdl: {},
      selectRows: [],
      selectedRowKeys: [],
      visible: false,
      confirmLoading: false,
      // 高级搜索 展开/关闭
      advanced: false,
      settingObj: {
        class_hour: '0',
        class_time: '0',
      },
      settingObjCopy: {
        class_hour: '0',
        class_time: '0',
      },
      // 查询参数
      keywords: '',
      queryParam: {
        school_id: this.$store.state.user.school,
      },
      // 表头
      columns: [
        {
          title: '学员姓名',
          width: 150,
          fixed: 'left',
          ellipsis: true,
          scopedSlots: { customRender: 'no' },
        },
        {
          title: '手机号',
          width: 150,
          dataIndex: 'main_phone',
        },
        {
          title: '所在校区',
          width: 200,
          dataIndex: 'structures_name',
        },
        {
          title: '课程名称',
          width: 150,
          dataIndex: 'course_name',
        },
        {
          title: '课程类型',
          dataIndex: 'course.type',
          align: 'center',
          width: 100,
          customRender(type) {
            return type == 1 ? '一对一' : '一对多'
          },
        },
        {
          title: '剩余数量',
          dataIndex: 'number',
          width: 150,
          scopedSlots: { customRender: 'number' },
        },
        {
          title: '跟进人',
          width: 100,
          dataIndex: 'user_name',
        },
        {
          title: '学管师',
          width: 100,
          dataIndex: 'academic_supervisor_name',
        },
        {
          title: '上次提醒时间',
          width: 150,
          scopedSlots: { customRender: 'last_remind_time' },
        },
        {
          title: '操作',
          dataIndex: 'updatedAt',
          fixed: 'right',
          align: 'right',
          scopedSlots: { customRender: 'action' },
        },
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {
        return contractList(Object.assign(parameter, this.queryParam, { keywords: this.keywords })).then((res) => {
          return res
        })
      },
      //课程列表
      courseList: [],
      classList: [],
      userList: [],
      //
    }
  },
  created() {
    this.getSetting()
    //获取课程列表
    coursesList({ pageSize: 999999, school_id: this.$store.state.user.school })
      .then((res) => {
        this.courseList = res.data
      })
      .catch((error) => {})

    classList({ pageSize: 999999, school_id: this.$store.state.user.school })
      .then((res) => {
        this.classList = res.data
      })
      .catch((error) => {})
    accountList({ pageSize: 999999, school_id: this.$store.state.user.school })
      .then((res) => {
        this.userList = res.data
      })
      .catch((error) => {})
  },
  computed: {
    hasSelected() {
      return this.selectedRowKeys.length > 0
    },
  },

  watch: {
    queryParam: {
      handler(newName, oldName) {
        this.$refs.table.refresh(true)
      },
      //immediate:true代表如果在 wacth 里声明了obj之后，就会立即先去执行里面的handler方法，
      immediate: false,
      deep: true, // 开启深度监听，默认是false
    },
  },
  methods: {
    handleChange2 (e) {
      if (e.target.checked == true) {
        this.queryParam.is_exceed = 1
      }
      if (e.target.checked == false) {
        this.queryParam.is_exceed = null
      }
      this.$refs.table.refresh()
    },
    nowClick (e) {
      this.$router.push({ name: 'studentInfo' })
    },
    handleEdit (record) {},
    handleSub (record) {
      if (record.status !== 0) {
        this.$message.info(`${record.no} 订阅成功`)
      } else {
        this.$message.error(`${record.no} 订阅失败，规则已关闭`)
      }
    },
    handleOk () {
      this.$refs.table.refresh()
    },
    toggleAdvanced () {
      this.advanced = !this.advanced
    },
    resetSearchForm () {
      this.queryParam = {
        date: moment(new Date()),
      }
    },
    getSetting () {
      getContractSetting({ school_id: this.$store.state.user.school, key: 'renewal-warning' })
        .then((res) => {
          if (res.value && !(res.value instanceof Array)) {
            this.settingObj = res.value
            this.settingObjCopy = JSON.parse(JSON.stringify(res.value))
          }
        })
        .catch((err) => {
          this.$message.error(err.data.message || '获取预警设置失败')
        })
    },
    settingTime () {
      let params = { school_id: this.$store.state.user.school, key: 'renewal-warning' }
      if (this.settingObj.class_hour || this.settingObj.class_hour == 0) {
        if (this.settingObj.class_time || this.settingObj.class_time == 0) {
          params.value = this.settingObj
          contractSetting(params)
            .then((res) => {
              this.getSetting()
              this.$refs.table.refresh(true)
              this.visible = false
            })
            .catch((err) => {
              this.visible = false
              this.$message.error(err.data.message || '设置失败')
            })
        } else {
          this.$message.error('剩余天数不能为空！')
          return
        }
      } else {
        this.$message.error('剩余课时不能为空！')
        return
      }
    },
    remind (e) {
      let arr = [
        {
          student_id: e.student_id,
          course_id: e.project_id,
          structures_id: e.structures_id,
        },
      ]
      contractRemind({ school_id: this.$store.state.user.school, ids: arr })
        .then((res) => {
          this.$refs.table.refresh()
          this.$message.success('提醒成功')
        })
        .catch((err) => {
          this.$message.error(err.data.message || '提醒失败')
        })
    },
    batchRemind () {
      let arr = []
      this.selectedRowKeys.forEach((val) => {
        arr.push({
          student_id: val.student_id,
          course_id: val.project_id,
          structures_id: val.structures_id,
        })
      })
      contractRemind({ school_id: this.$store.state.user.school, ids: arr })
        .then((res) => {
          this.selectedRowKeys = []
          this.selectRows = []
          this.$refs.table.refresh()
          this.$message.success('提醒成功')
        })
        .catch((err) => {
          this.$message.error(err.data.message || '提醒失败')
        })
    },
    handleCancel () {
      this.visible = false
    },
    signUp (e, data, courseID) {
      if (courseID) {
        this.$router.push({
          name: 'apply',
          query: { id:Number(e), structure_id: data, courseID: courseID },
        })
      } else {
        this.$router.push({ name: 'apply', query: { id:Number(e), structure_id: data } })
      }
    },
    more () {
      this.advanced = !this.advanced
    },
    onSelectChange (selectRows, selectedRowKeys) {
      this.selectRows = selectRows
      this.selectedRowKeys = selectedRowKeys
    }
  }
}
</script>
<style lang="less" scoped>
.expand_warning {
  margin: 16px 0;
  background-color: #fff0e7;
  border-radius: 4px;
}
#moreButton {
  position: absolute;
  top: 34px;
  right: 20px;
}
</style>